package controller

import (
	"ginEssential/common"
	"ginEssential/model"
	"ginEssential/response"
	"ginEssential/vo"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	"strconv"
)

type IRoleController interface {
	RestController
}

type RoleController struct {
	DB *gorm.DB
}

func NewRoleController() RoleController {
	db := common.GetDB()
	db.AutoMigrate(model.Role{})
	return RoleController{DB: db}
}

func (r RoleController) Create(ctx *gin.Context) {
	var requestRole vo.CreateRoleRequest

	if err := ctx.ShouldBind(&requestRole); err != nil {
		response.Fail(ctx, "数据验证错误，角色名称必填", nil)
		return
	}

	role := model.Role{RoleName: requestRole.RoleName, RoleDesc: requestRole.RoleDesc}

	r.DB.Create(&role)
	response.Success(ctx, gin.H{"role": role}, "")
}

func (r RoleController) Update(ctx *gin.Context) {
	var requestRole vo.CreateRoleRequest

	if err := ctx.ShouldBind(&requestRole); err != nil {
		response.Fail(ctx, "数据验证错误，角色名称必填", nil)
		return
	}

	// 获取path中的参数
	roleId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	var updateRole model.Role
	if r.DB.First(&updateRole, roleId).RecordNotFound() {
		response.Fail(ctx, "角色不存在", nil)
		return
	}

	r.DB.Model(&updateRole).Update("roleName", requestRole.RoleName).Update("roleDesc", requestRole.RoleDesc)

	response.Success(ctx, gin.H{"role": updateRole}, "修改成功")
}

func (r RoleController) Show(ctx *gin.Context) {
	// 获取path中的参数
	roleId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	var Role model.Role
	if r.DB.First(&Role, roleId).RecordNotFound() {
		response.Fail(ctx, "角色不存在", nil)
		return
	}
	response.Success(ctx, gin.H{"role": Role}, "查询成功")
}

func (r RoleController) Delete(ctx *gin.Context) {
	// 获取path中的参数
	roleId, _ := strconv.Atoi(ctx.Params.ByName("id"))

	if err := r.DB.Delete(model.Role{}, roleId).Error; err != nil {
		response.Fail(ctx, "删除失败，请重试", nil)
		return
	}
	response.Success(ctx, nil, "删除成功")
}
